package com.example.demo.common.util;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.example.demo.common.util.entity.ExcelConfig;
import com.example.demo.config.CommonReadListener;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class ExcelUtil{

    public static <T> List<T> read(String filePath, Class<T> clazz, ExcelConfig excelConfig){
        CommonReadListener<T> commonReadListener = new CommonReadListener<>();
        try {
            EasyExcel.read(filePath, clazz, commonReadListener)
                    .extraRead(CellExtraTypeEnum.COMMENT)
                    .sheet(Optional.ofNullable(excelConfig.getSheetName()).orElse(null))
                    .headRowNumber(Optional.ofNullable(excelConfig.getContextIndex()).orElse(0))
                    .doRead();
        } catch(Exception e){
            log.error("导入报错: " + e.getMessage() +",堆栈信息: " + e.getStackTrace());
        }
        return commonReadListener.getList();
    }

    public static <T> void write(String filePath, Class<T> clazz, ExcelConfig excelConfig, List<T> list){
        try {
            EasyExcel.write(filePath, clazz)
                    .sheet(Optional.ofNullable(excelConfig.getSheetName()).orElse(null))
                    .doWrite(list);
        } catch(Exception e){
            log.error("导出报错：" + e.getMessage() + ",堆栈信息: " + e.getStackTrace());
        }
    }
}
